<?php
declare(strict_types=1);

namespace think\admin\test\controller;

use think\admin\Controller;
use think\admin\test\service\OrderService;
use think\admin\test\service\PaymentService;
use think\admin\test\service\UserService;
use think\admin\test\service\ProductService;
use think\admin\exception\BusinessException;
use think\Response;

class OrderController extends Controller
{
    /**
     * 服务类型定义
     */
    public const SERVICE_ORDER = 'order';
    public const SERVICE_PAYMENT = 'payment';
    public const SERVICE_USER = 'user';
    public const SERVICE_PRODUCT = 'product';

    /**
     * 初始化
     * @throws BusinessException
     */
    protected function initialize(): void
    {
        // 设置主服务
        $this->service = new OrderService($this->app);

        // 注册关联服务
        $this->registerService(self::SERVICE_PAYMENT, new PaymentService($this->app));
        $this->registerService(self::SERVICE_USER, new UserService($this->app));
        $this->registerService(self::SERVICE_PRODUCT, new ProductService($this->app));
    }

    /**
     * 创建订单
     * @return Response
     */
    public function create(): Response
    {
        return $this->catchException(function() {
            // 获取请求数据
            $data = $this->request->post();

            // 验证数据
            $this->validate($data, 'Order.create');

            // 获取用户服务检查用户状态
            /** @var UserService $userService */
            $userService = $this->getService(self::SERVICE_USER);
            $user = $userService->getUserInfo($data['user_id']);
            if ($user['status'] !== 1) {
                throw new BusinessException('用户状态异常');
            }

            // 获取商品服务检查商品状态
            /** @var ProductService $productService */
            $productService = $this->getService(self::SERVICE_PRODUCT);
            $product = $productService->getProductInfo($data['product_id']);
            if ($product['status'] !== 1) {
                throw new BusinessException('商品已下架');
            }

            // 创建订单
            /** @var OrderService $orderService */
            $orderService = $this->service;
            $result = $orderService->createOrder($data);

            return $this->success($result, '创建成功');
        });
    }

    /**
     * 支付订单
     * @param int $id
     * @return Response
     */
    public function pay(int $id): Response
    {
        return $this->catchException(function() use ($id) {
            // 验证订单ID
            if ($id <= 0) {
                throw new BusinessException('订单ID无效');
            }

            /** @var OrderService $orderService */
            $orderService = $this->service;
            
            // 获取订单信息
            $order = $orderService->getOrderDetail($id);
            if (empty($order)) {
                throw new BusinessException('订单不存在');
            }

            // 检查用户状态
            /** @var UserService $userService */
            $userService = $this->getService(self::SERVICE_USER);
            $user = $userService->getUserInfo($order['user_id']);
            if ($user['status'] !== 1) {
                throw new BusinessException('用户状态异常');
            }

            // 检查商品状态
            /** @var ProductService $productService */
            $productService = $this->getService(self::SERVICE_PRODUCT);
            $product = $productService->getProductInfo($order['product_id']);
            if ($product['status'] !== 1) {
                throw new BusinessException('商品已下架');
            }

            // 执行支付
            if ($orderService->payOrder($id)) {
                return $this->success([], '支付成功');
            }

            return $this->error('支付失败');
        });
    }

    /**
     * 取消订单
     * @param int $id
     * @return Response
     */
    public function cancel(int $id): Response
    {
        return $this->catchException(function() use ($id) {
            // 验证订单ID
            if ($id <= 0) {
                throw new BusinessException('订单ID无效');
            }

            /** @var OrderService $orderService */
            $orderService = $this->service;
            
            // 获取订单信息
            $order = $orderService->getOrderDetail($id);
            if (empty($order)) {
                throw new BusinessException('订单不存在');
            }

            // 检查用户状态
            /** @var UserService $userService */
            $userService = $this->getService(self::SERVICE_USER);
            $user = $userService->getUserInfo($order['user_id']);
            if ($user['status'] !== 1) {
                throw new BusinessException('用户状态异常');
            }

            // 执行取消
            if ($orderService->cancelOrder($id)) {
                return $this->success([], '取消成功');
            }

            return $this->error('取消失败');
        });
    }

    /**
     * 获取订单详情
     * @param int $id
     * @return Response
     */
    public function detail(int $id): Response
    {
        return $this->catchException(function() use ($id) {
            // 验证订单ID
            if ($id <= 0) {
                throw new BusinessException('订单ID无效');
            }

            /** @var OrderService $orderService */
            $orderService = $this->service;
            
            // 获取订单详情
            $order = $orderService->getOrderDetail($id);
            if (empty($order)) {
                throw new BusinessException('订单不存在');
            }

            // 获取用户信息
            /** @var UserService $userService */
            $userService = $this->getService(self::SERVICE_USER);
            $order['user'] = $userService->getUserInfo($order['user_id']);

            // 获取商品信息
            /** @var ProductService $productService */
            $productService = $this->getService(self::SERVICE_PRODUCT);
            $order['product'] = $productService->getProductInfo($order['product_id']);

            // 获取支付信息
            /** @var PaymentService $paymentService */
            $paymentService = $this->getService(self::SERVICE_PAYMENT);
            $order['payment'] = $paymentService->getPaymentByOrderId($order['id']);

            return $this->success($order);
        });
    }

    /**
     * 获取订单列表
     * @return Response
     */
    public function list(): Response
    {
        return $this->catchException(function() {
            // 获取查询参数
            $params = $this->request->get();

            // 验证参数
            $this->validate($params, 'Order.list');

            /** @var OrderService $orderService */
            $orderService = $this->service;
            
            // 获取订单列表
            $list = $orderService->getOrderList($params);

            // 补充关联数据
            if (!empty($list['items'])) {
                /** @var UserService $userService */
                $userService = $this->getService(self::SERVICE_USER);
                /** @var ProductService $productService */
                $productService = $this->getService(self::SERVICE_PRODUCT);

                foreach ($list['items'] as &$item) {
                    // 补充用户信息
                    $item['user'] = $userService->getUserInfo($item['user_id']);
                    // 补充商品信息
                    $item['product'] = $productService->getProductInfo($item['product_id']);
                }
            }

            return $this->success($list);
        });
    }
} 